package com.yxj.securityhello.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxj.securityhello.domain.Svsuser;
import com.yxj.securityhello.domain.vo.LoginUser;
import com.yxj.securityhello.mapper.SvsuserMapper;
import com.yxj.securityhello.service.UserService;
import com.yxj.securityhello.util.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author yangxuejiao
 * @description
 * @createDate 2025/11/2 23:00
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<SvsuserMapper, Svsuser> implements UserService {

    private final AuthenticationManager authenticationManager;
    @Override
    public String login(Svsuser user) {
        //1.封装Authenticarion对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        //2.进行校验
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if(Objects.isNull(authenticate)) {
            throw new RuntimeException("登录失败");
        }
        //给的用户信息
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        //生成Jwt,使用fastjson的方法，吧对象转成字符串
        String jsonString = JSON.toJSONString(loginUser);
        //调用Jwt工具类生成Jwt令牌
        String jwt = JwtUtils.createJwt(jsonString, null);
        return jwt;
    }
}
